<template>
  <div class="main-div">
    <Row>
      <Col span="24"/>

      <bus-table
        :single-show.sync="busShow"
        :on-ok="confirmDialogSingleEvent"
        :existData="mainTable"
      ></bus-table>
      <bus-table-multiple-dialog
        :bus-child-show.sync="busChildShow"
        :on-ok="confirmDialogMultipleEvent"
        :existData="ruleForm.tableData">


      </bus-table-multiple-dialog>


      <Card>
        <p slot="title">业务对象</p>

        <Form ref="formInline" :model="formInline" :label-width="80" inline :rules="ruleValidate">
          <FormItem prop="groupName" label="分类">
            <treeselect v-model="formInline.groupName"
                        :normalizer="normalizer"
                        :multiple="false"
                        @select="selectTree"
                        @input="clearOnSelect"

                        placeholder="请选择"
                        :options="categoryData"/>

          </FormItem>


          <FormItem prop="objName" label="名字">
            <Input v-model="formInline.objName" type="text" clearable/>
          </FormItem>

          <FormItem prop="objKey" label="别名">
            <Input v-model="formInline.objKey" type="text" :disabled="edit" clearable/>
          </FormItem>
          <FormItem prop="description" label="主业务表">
            <el-tag type="success"
                    v-if="(mainTable)">
              {{mainTable.description}}

            </el-tag>
            <Button type="primary" style="margin-bottom: 2px;margin-right: 15px;"
                    @click="addBus">选择
            </Button>
            <!--          <Input v-model="formInline.mainTable" type="hidden"/>-->

          </FormItem>
          <FormItem prop="objDesc" label="描述">
            <Input v-model="formInline.objDesc" type="text"  clearable/>
          </FormItem>

        </Form>

        <el-button   @click="add"  type="success">添加子业务实体</el-button>

        <el-button type="primary"   @click="save"  :loading="loading">保存</el-button>



      </Card>

      <Card style="margin-top: 5px">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"

          style="margin-top: 10px">
          <el-table
            class="n-table--border"
            stripe
            highlight-current-row
            :data="ruleForm.tableData"
          >
            <el-table-column label="类型"
                             width='200'
                             fixed
                             show-overflow-tooltip


            >

              <template slot-scope="scope">

                <el-form-item :prop="'tableData.' + scope.$index + '.type'">

                  <el-select v-model="scope.row.type" placeholder="请选择"
                             @change="((val)=>{selectDataTypeChanged(val,  scope.$index)})">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>


                </el-form-item>


              </template>

            </el-table-column>
            <el-table-column label="描述"

                             width='200'
                             show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{scope.row.tableComment}}
              </template>
            </el-table-column>
            <el-table-column label="表名"
                             width='200'
                             show-overflow-tooltip>
              <template slot-scope="scope">
                {{scope.row.tableKey}}
              </template>
            </el-table-column>

            <el-table-column label="操作"
                             fixed="right"
            >
              <template slot-scope="scope">
                <el-form-item>
                  <el-button type="danger" plain @click="delField(scope.$index)">
                    删除
                  </el-button>

                </el-form-item>

              </template>
            </el-table-column>

          </el-table>

        </el-form>


      </Card>




      <!--        <Table border  ref="currentRowTable" height="450"-->
      <!--               :columns="tableColumns" :data="tableData" style="padding-left: 10px;padding-top: 10px">-->
      <!--        </Table>-->


      </Col>

    </Row>
  </div>

</template>

<script>
  import {getTaskData} from '@/api/analy'
  // import the component
  import Treeselect from '@riophae/vue-treeselect'
  // import the styles
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import busTable from '@/views/common/busTable'
  import busTableMultipleDialog from '@/views/common/busTableMultipleDialog'
  import {
    getTypesByKey,
    businessTableCreate,
    businessObjectGet,
    businessObjectSave
  } from '@/api/form'
  import {isColumnKey, attrLengthValidator} from '@/utils/validate'

  export default {
    name: 'Task',
    components: {Treeselect, busTable, busTableMultipleDialog},

    data() {


      return {
        loading:false,

        busShow: false,
        busChildShow: false,
        edit: false,
        ruleForm: {
          tableData: [],
        },
        rules: {
          description: [{required: true, message: "  ", trigger: "blur"}],
          decimalLength: [{required: true, message: "  ", trigger: "blur"}],
          attrLength: [{
            validator: attrLengthValidator,
            trigger: "blur"
          }],
          columnKey: [{required: true, message: "  ", trigger: "blur"}, {validator: isColumnKey, trigger: "blur"}],
        },

        options: [{
          value: 'oneToOne',
          label: '一对一'
        }, {
          value: 'oneToMany',
          label: '一对多'
        }],
        tableFormRules: {
          description: {type: "string", required: true, message: "必填字段", trigger: "change"},
        },
        ruleValidate: {
          groupName: [
            {required: true, message: '请选择分类', trigger: 'blur,change'}
          ],
          objName: [
            {required: true, message: '请输入名字', trigger: 'blur'}
          ],
          objKey: [
            {required: true, message: '请输入别名', trigger: 'blur'}
          ],
          mainTable: [
            {required: true, message: '请选择主表', trigger: 'blur'}
          ],
        },
        // define the default value
        value: null,
        value: '',
        formatOptions: [{
          value: 'yyyy-MM-dd HH:mm:ss',
          label: 'yyyy-MM-dd HH:mm:ss'
        }, {
          value: 'yyyy-MM-dd',
          label: 'yyyy-MM-dd'
        }, {
          value: 'HH:mm:ss',
          label: 'HH:mm:ss'
        }],
        formatValue: 'yyyy-MM-dd HH:mm:ss',
        formInline: {
          createdTable: 'false',
          objName: '',
          formKey: '',
          groupId: '',
          groupName: null,
          modelName: '',
          tableName: null,
          objDesc: '',
          objKey: '',
          id: '',
          mainTable: ''
        },

        tableData: [],
        tableHeight: 450,
        queryDate: [],
        total: 0,
        chartVisible: false,
        chartData: {},
        sellerId: 0,
        shopName: [],
        queryForm: {
          groupId: '',
          page: 1,
          limit: 10
        },
        categoryData: [],
        existTableData: [],
        existData: [],
        mainTable: null,
        childTable: null,
      }
    },
    mount() {
      this.getData()
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
    },
    created() {
      var query = this.$route.query
      var operate = query.operate
      var edit = query.edit
      if (edit) {
        this.edit = JSON.parse(edit);

      }else{
      }

      if (query.id) {
        this.formInline.id = query.id
        this.initData();
      }
      if (operate) {
        this.formInline.type = operate;
      }
      this.initExternal();
      this.getData()

    },

    methods: {
      addBus: function () {
        this.busShow = true
      },

      confirmDialogSingleEvent: function (data) {
        if (data) {
          this.mainTable = data;
          this.mainTable.description=data.modelName
          this.formInline.mainTable = data.tableName
        }
      },
      confirmDialogMultipleEvent: function (data) {
        if (data) {
          let obj = {};
          this.ruleForm.tableData.forEach(item => {
            let key = item.tableKey;
            obj[key] = item.type;
          })

          this.ruleForm.tableData = data;
          //oneToOne
          this.ruleForm.tableData.forEach(item => {
            if (obj[item.tableKey]){
              item.type=obj[item.tableKey];
            }else{
              item.type = 'oneToOne';
            }
            item.tableComment= item.description
            item.tableKey= item.tableName

          })
        }
      },
      initExternal: function () {
        if (this.formInline.type == 'external') {
          businessTableColumnMetadataInfo().then((response) => {
            if (response.code == 0) {
              this.existTableData = response.data;
            }

          })
        }
      },
      operateDisabled: function (data) {
        if (this.formInline.type == 'inner' && (this.formInline.createdTable == "false" || this.formInline.createdTable == false)) {
          return false;
        } else if (this.formInline.type == 'inner' && (this.formInline.createdTable == "true" || this.formInline.createdTable == true)) {
          if (data.id) {
            return true
          } else {
            return false;
          }
        }
        return true
      },
      operateShowExistdData: function (data) {
        if (this.formInline.type == 'external') {
          return true;
        } else {
          return false;
        }
      },
      operateDisabledDelBtn: function (data) {
        if (this.formInline.type == 'inner' && (this.formInline.createdTable == "false" || this.formInline.createdTable == false)) {
          return true;
        } else if (this.formInline.type == 'inner' && (this.formInline.createdTable == "true" || this.formInline.createdTable == true)) {
          if (data.id) {
            return false
          } else {
            return true;
          }
        }
        return false
      },
      createTable: function () {

        businessTableCreate(this.formInline.id).then((response) => {
          if (response.code == 0) {
            this.$message({"duration":800,message:'操作成功',type:'success',customClass:'zZindex'});

            this.initData()
          }


        })


      },
      initData: function () {
        businessObjectGet(this.formInline.id).then((response) => {
          if (response.code == 0) {
            var data = response.data;
            this.formInline = data;
            var relationJson = JSON.parse(data.relationJson);
            var description;
            if (relationJson.tableComment){
              description=relationJson.tableComment
            }else{
              description=relationJson.tableKey
            }
            this.mainTable = {

              description: description,
              tableKey: relationJson.tableKey,
              type: "main"
            }
            this.formInline.mainTable = this.mainTable
            var children = relationJson.children;
            this.ruleForm.tableData = children;
            this.childTable=children
            this.childTable.forEach(item => {
              item.description= item.tableComment
              item.tableName= item.tableKey

            })
          }


        })
      },
      selectTree: function (node, instanceId) {
        this.formInline.groupId = node.id
        this.formInline.groupName = node.title
        this.validateFormInline()

      },

      clearOnSelect: function (node, instanceId) {
        if (!node) {
          this.formInline.groupId = ''
          this.formInline.groupName = null
          this.validateFormInline()

        }
      },
      clearExistTableOnSelect: function (node, instanceId) {
        if (!node) {
          this.formInline.tableName = null
        }
      },
      selectExistTableTree: function (node, instanceId) {
        businessTableColumnMetadataInfoByTableName(node.tableName).then((response) => {
          if (response.code == 0) {
            var data = response.data;
            this.ruleForm.tableData = data;


          }


        })


      },
      validateRuleForm: function () {
        this.$nextTick(() => {
          this.$refs['ruleForm'].validate((valid) => {

          })
        })

      },
      validateFormInline: function () {
        this.$nextTick(() => {
          this.$refs['formInline'].validate((valid) => {

          })
        })

      },
      save: function () {
        this.$refs['formInline'].validate((valid) => {
          if (valid) {
            var data = {};
            var formData = this.formInline;
            if (!formData.mainTable) {
              this.$message({"duration":800,message:'主业务表必须选择',type:'warning',customClass:'zZindex'});

              return
            }
            const obj = JSON.parse(JSON.stringify(this.formInline))
            var type = "main"
            var relation = {
              "tableKey": this.mainTable.tableName==undefined?this.mainTable.tableKey:this.mainTable.tableName,
              "tableComment": this.mainTable.description,
              "type": type
            }

            this.$refs['ruleForm'].validate((valid2) => {
              if (valid2) {
                var columnTable = this.ruleForm.tableData;
                var children = [];
                delete (obj['relationJson'])
                delete (obj['relationJsonByte'])
                for (var i = 0; i < columnTable.length; i++) {
                  var curnnenetData = columnTable[i];
                  children.push({
                    "type": curnnenetData.type,
                    "tableComment": curnnenetData.tableComment,
                    "tableKey": curnnenetData.tableKey
                  })
                }
                relation["children"] = children;
                obj["relation"] = relation

                businessObjectSave(obj).then((response) => {
                  if (response.code == 0) {
                    this.formInline.id=response.data.id;
                    this.$confirm('更新业务对象成功,是否继续操作？', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(() => {
                      //点击确定按钮的操作
                    }).catch(() => {
                      // 调用全局挂载的方法
                      this.$store.dispatch('tagsView/delView', this.$route)
                      // 返回上一步路由
                      this.$router.go(-1)
                    });
                  }else{
                    this.$message({"duration":800,message:response.msg,type:'warning',customClass:'zZindex'});

                  }
                })
              }
            })


          } else {

            return
          }


        })
      },
      selectDataTypeChanged: function (value, index) {

        this.ruleForm.tableData[index].type = value;
      }
      ,

      delField: function (index) {
        this.ruleForm.tableData.splice(index, 1);
        this.$message({"duration":800,message:'删除成功',type:'success',customClass:'zZindex'});

      }
      ,
      disabledDelBtn: function (row) {

        for (var i = 0; i < this.existData.length; i++) {
          if (row === this.existData[i]) {
            return true;
          }
        }
        return false;
      }
      ,
      add: function () {
        this.busChildShow = true
      }
      ,
      queryFormCreateTime: function (e) {
        this.queryForm.createTime = e
      }
      ,
      refreshTask: function (data) {
        if (data[0].parentId == '-1') {
          this.queryForm.typeKey = ''
        } else {
          this.queryForm.typeKey = data[0].typeKey
        }
        this.queryForm.createTime = ''
        this.queryDate = []
        this.queryForm.page=1

        this.queryForm.whereSql = ''
        this.getData()
      }
      ,
      queryMethod: function () {
        var name = this.queryForm.name
        var whereSql = ''
        var createTime = this.queryForm.createTime
        if (createTime) {
          if (createTime[0]) {
            whereSql = "  CREATE_TIME_  between '" + createTime[0] + "' and " + "'" + createTime[1] + "'"
          }
        }
        this.queryForm.whereSql = whereSql
        getTaskData(this.queryForm).then((response) => {
          this.tableData = response.data
          this.total = response.count;

        })
      }
      ,
//后台返回的数据如果和VueTreeselect要求的数据结构不同，需要进行转换
      normalizer(node) {
        //去掉children=[]的children属性
        if(node.children && !node.children.length){
          delete node.children;
        }
        return {
          id: node.title,
          label: node.title,
          children: node.children
        }
      },
      existTableNormalizer(node) {
        return {
          id: node.tableName,
          label: node.tableComment,
          children: node.children
        }
      },
      getData: function () {
        getTypesByKey().then((response) => {
          this.categoryData = response.data
        })
      }
      ,
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.getData()
      }
      ,
      handleClick(data) {
        this.$router.push({name: 'handleRunTask', query: {t: new Date().getTime(), 'taskId': data.id}})
      }
      ,
      search() {
        this.queryForm.page = 1
        this.queryMethod()
      }
      ,
      reset() {
        this.queryForm.name = ''
        this.queryForm.createTime = ''
        this.queryForm.whereSql = ''
        this.queryDate = []
        this.getData()
      }

    }

  }

</script>
<style lang="scss" scoped>

  .main-div {
    background-color: #f3f3f3!important;
  }

  .task-card {
    margin-top: 10px;
  }

  .vue-treeselect {
    max-width: 180px;
  }

  .cell {
    max-height: 54px !important;
    overflow: auto !important;
  }


</style>
